#!/bin/bash

#  ren - the small script for user to rename files.
#  desinger: Swaper@RainStudio

slfName=$(basename $0)
oldIFS=$IFS

strPfx=""
strExt=""
strName=""
strSfx=""
mvDir=0
hasName=0
hasExt=0

count=$[$#-1];
k=0

IFS=""
for i in $*; do
  if [ ${i:0:3} == "/p:" ]; then
    strPfx=${i:3}
    count=$[$count-1]
  fi
  if [ ${i:0:3} == "/f:" ]; then
    strName=${i:3}
    count=$[$count-1]
    hasName=1
  fi
  if [ ${i:0:3} == "/e:" ]; then
    strExt=${i:3}
    count=$[$count-1]
    hasExt=1
  fi
  if [ ${i:0:3} == "/s:" ]; then
    strSfx=${i:3}
    count=$[$count-1]
  fi
  if [ ${i:0:3} == "/n:" ]; then
    j=3
    while [ ${i:j:1} == "0" ]; do 
      j=$[$j+1]
    done
    if [ $j -lt ${#i} ]; then
      l=$j
      while [ $l -lt ${#i} ]; do
        case ${i:$l:1} in 
          (0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) ;;
          *) break
        esac
        l=$[$l+1]
      done  
      if [ $l -eq ${#i} ]; then
        k=${i:j}
        count=$[$count+${i:j}]
      fi
    fi
    count=$[$count-1]
  fi
  if [ ${i:0:2} == "/d" ]; then
    mvDir=1
    count=$[$count-1]
  fi
done
if [ -z $strPfx ] && [ $hasName -eq 0 ] && 
  [ $hasExt -eq 0 ] && [ -z $strSfx ]; then
  echo "$slfName: usage: $slfName files /p:prefix /f:newname /e:newext /s:suffix"
  echo "$slfName: use option /d to move direcotries."
  echo "$slfName: use option /n:number to set additional number." 
  echo
  echo "examples:"
  echo "$slfName * /p:My /f:Document /n:1 /e:txt"
  echo "$slfName * /s:-2000:00:00"
  IFS=$oldIFS
  exit 1
fi

for i in $*; do
  if [ -e $i ] && [ ${i:0:3} != "/p:" ] && [ ${i:0:3} != "/f:" ] && 
    [ ${i:0:3} != "/n:"  ] && [ ${i:0:3} != "/s:" ] && [ ${i:0:2} != "/d" ]; then
    if [ -d $i ] && [ $mvDir -ne 1 ]; then
      echo "ren: '$i' is a direcotry" 
      continue
    fi
    l=${#i}
    for((j=$[$l-1]; j > 0; j=$[$j-1])); do
      if [ ${i:$j:1} == "." ]; then
        break
      fi
    done
    if ! [ $j -eq 0 ]; then
      if [ $hasName -eq 0 ]; then
        filename=${i:0:$j}
      else
  strPz=""
  for((m=${#k}; m < ${#count}; m=$[$m+1])); do
          strPz=0$strPz
        done
        filename=$strName$strPz$k
        k=$[$k+1]
      fi
      if [ $hasExt -eq 0 ]; then
        extname=${i:$j}
      else
        extname=.$strExt
      fi
    else
      if [ $hasName -eq 0 ]; then
        filename=$i
      else
  strPz=""
  for((m=${#k}; m < ${#count}; m=$[$m+1])); do
          strPz=0$strPz
        done
        filename=$strName$strPz$k
        k=$[$k+1]
      fi
      if [ $hasExt -eq 0 ]; then
        extname=""
      else
        extname=.$strExt
      fi
    fi
    mv -i $i $strPfx$filename$extname$strSfx
  fi
done

IFS=$oldIFS
